<template>
  <div class="order-apply-invoice">
    <div ref="chartRef" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch, nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  config: {
    type: Object,
    default: () => ({
      xAxisData: [],
      yAxisData: []
    }),
  },
})

const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 销毁旧实例（避免内存泄漏）
  if (chartInstance) {
      chartInstance.dispose()
      chartInstance = null
  }
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return
  
  const option = {
    legend: {
        right: '50px',
        top: '20px',
        data: [props.config.legendName]
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Array.from(props.config.xAxisData || [])
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: props.config.legendName,
        data: Array.from(props.config.yAxisData || []),
        type: 'bar',
        barWidth: '40%', // 更美观的柱宽
        itemStyle: {
          color: '#5470c6' // 添加默认颜色
        },
        label: {
            show: true, // 显示标签
            position: 'top',
            formatter: '{c}个', // 显示数据值
          }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 监听配置变化
watch(() => props.config, () => {
  // 如果实例不存在，先初始化
  if (!chartInstance) {
      initChart()
  } else {
      updateChart()
  }
}, { deep: true })

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>